import { getSubCategoryGoodListAPI } from "@/apis/category";
import { GoodListRequestDataSortFieldType, GoodListRequestDataType } from "@/types/category";
import { GoodInterface } from "@/types/good";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

export const useGoodList = function () {
    // 获取路由信息
    const route = useRoute();

    // GoodList请求携带数据
    const goodListRequestData = ref<GoodListRequestDataType>({
        categoryId: route.params.id as string,
        page: 1,
        pageSize: 20,
        sortField: 'publishTime',
    });

    // GoodList数据
    const goodList = ref<Array<GoodInterface>>([]);

    // 加载商品列表数据方法
    const getGoodList = async () => {
        const response = await getSubCategoryGoodListAPI(goodListRequestData.value);
        goodList.value = response.data.result.items;
    };

    // 页面初次加载商品数据
    onMounted(() => getGoodList());

    // tab切换回调
    const tabChange = (name: GoodListRequestDataSortFieldType) => {
        // 修改请求参数
        goodListRequestData.value.sortField = name;
        goodListRequestData.value.page = 1;
        // 重置无限滚动功能
        infiniteScrollDisabled.value = false;
        // 重新请求商品数据
        getGoodList();
    };

    // 无限滚动加载方法
    const infiniteScrollDisabled = ref(false);
    const infiniteScroll = async () => {
        // 页数增加
        goodListRequestData.value.page++;
        // 拼接新旧数据
        const response = await getSubCategoryGoodListAPI(goodListRequestData.value);
        goodList.value = [...goodList.value, ...response.data.result.items];
        // 加载完毕停止监听
        if (response.data.result.page === response.data.result.pages) {
            infiniteScrollDisabled.value = true;
        }
    };

    return { goodList, tabChange, infiniteScroll, infiniteScrollDisabled };
};